package com.uw.uwregistry.meta;

import com.alibaba.fastjson.JSON;
import com.uw.uwregistry.constant.UWRegistryConstant;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务实例元信息
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = {"scheme", "ip", "port", "contextPath"})
public class InstanceMeta {


    private String scheme;
    private String ip;
    private Integer port;
    private String contextPath;

    // 状态，0：下线，1：上线
    private Integer status = 1;

    private Map<String, String> parameters = new HashMap<>();

    public String instanceSign() {
        return String.join(UWRegistryConstant.SEPARATOR, Arrays.asList(ip, port.toString()));
    }

    public String toUrl() {
        if (StringUtils.hasText(contextPath)) {
            return String.format("http://%s:%d/%s", ip, port, contextPath);
        }
        return String.format("http://%s:%d/", ip, port);
    }

    public String toMetas() {
        return JSON.toJSONString(this.getParameters());
    }


    /**
     * @param url "http://%s:%d/%s"
     */
    public static InstanceMeta fromUrl(String url) {
        String[] split = url.split("://");
        String[] split2 = split[1].split(":");
        String[] split3 = split2[1].split("/");

        String scheme = split[0];
        String host = split2[0];
        Integer port = Integer.valueOf(split3[0]);
        String contextPath = split3.length >= 2 ? split3[1] : null;

        return InstanceMeta.builder()
                .scheme(scheme)
                .ip(host)
                .port(port)
                .contextPath(contextPath)
                .parameters(new HashMap<>())
                .build();
    }

    public static InstanceMeta http(String host, Integer port) {
        return InstanceMeta.builder()
                .scheme("http")
                .ip(host)
                .port(port)
                .contextPath("uwrpc")
                .parameters(new HashMap<>())
                .build();
    }

}